from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization

# 加载私钥
with open("private_key.txt", "rb") as f:
    private_pem = f.read()
    private_key = serialization.load_pem_private_key(
        private_pem,
        password=None
    )

print(private_key)

# 加载公钥
with open("public_key.txt", "rb") as f:
    public_pem = f.read()
    public_key = serialization.load_pem_public_key(public_pem)
    

# 加密
plaintext = b"Hello, World!"
ciphertext = public_key.encrypt(
    plaintext,
    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                 algorithm=hashes.SHA256(),
                 label=None)
)
print("加密后的结果:", ciphertext)

# 解密
decrypted_text = private_key.decrypt(
    ciphertext,
    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                 algorithm=hashes.SHA256(),
                 label=None)
)
print("解密后的结果:", decrypted_text.decode())



"""from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization

# 生成 RSA 密钥对
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()

# 保存私钥到文件
private_pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)

with open("private_key.txt", "wb") as f:
    f.write(private_pem)

# 保存公钥到文件
public_pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

with open("public_key.txt", "wb") as f:
    f.write(public_pem)

def createPublicKey(self):
        with open("private_key.txt", "rb") as f:
            private_pem = f.read()
            private_key = serialization.load_pem_private_key(
                private_pem,
                password=None
            )
            public_key = private_key.public_key() #生成公钥
            return public_key.public_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PublicFormat.SubjectPublicKeyInfo
            )


    def encode(self,data:str,publickey:str):
        pass
"""